<?php
/**
 * 返回json数据
 * @param int $code
 * @param string $msg
 * @param null $data
 */
function returnJson($code=200, $msg="成功", $data=null): \Illuminate\Http\JsonResponse
{
    return response()->json([
        'code'  => $code,
        'msg'  => $msg,
        'data'  => $data,
    ]);
}

function returnErrorJson($msg="请求失败",$code=400, $data=null): \Illuminate\Http\JsonResponse
{
    return response()->json([
        'code'  => $code,
        'msg'  => $msg,
        'data'  => $data,
    ]);
}


/**
 * 计算距离
 * @param $lat1
 * @param $lng1
 * @param $lat2
 * @param $lng2
 * @return int
 */
function getDistance($lat1, $lng1, $lat2, $lng2){
    if( !$lat1 || !$lng1 || !$lat2 || !$lng2  ){
        return 0;
    }

    // 将角度转为狐度
    $radLat1 = deg2rad($lat1);// deg2rad()函数将角度转换为弧度
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);

    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;

    $s = 2 * asin(sqrt(pow(sin($a / 2), 2)+cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;

    return sprintf('%.2f', $s);

}

/**
 * @param $uid
 * @param $type 1-补贴订单订单号，2-结算订单号，3-vip订单号,4-品鉴金订单号,5-平台业务订单号,6-提现订单号
 * @return string
 */
function getOrderNo($uid, $type): string
{
    $orderNo = '';
    switch ( $type ){
        case 1: $orderNo = 'SU'.$uid.'-'.time().mt_rand(10000, 99999);break;
        case 2: $orderNo = 'SE'.$uid.'-'.time().mt_rand(10000, 99999);break;
        case 3: $orderNo = 'VIP'.$uid.'-'.time().mt_rand(10000, 99999);break;
        case 4: $orderNo = 'PIN'.$uid.'-'.time().mt_rand(10000, 99999);break;
        case 5: $orderNo = 'PLAT'.$uid.'-'.time().mt_rand(10000, 99999);break;
        case 6: $orderNo = 'WITH'.$uid.time().mt_rand(10000, 99999);break;
        default:
    }
    return $orderNo;
}

/**
 * 获取微信交易手续费
 * @param $amount
 */
function getWxFee($amount): float
{
    return round($amount * 0.006, 2);
}

/**
 * 获取提现手续费
 * @param $amount
 */
function getWithdrawalFee($amount): float
{
    return round($amount * config('app.withdrawal_fee'), 2);
}

/**
 * 回调日志
 * @param $data
 * @param $title
 */
function callbackLog($data, $title){
    \DB::table('payment_callback_log')->insert([
        'text'  => json_encode($data),
        'title'  => $title,
        'created_at'    => getDt()
    ]);
}

/**
 * 接口辅助日志
 * @param $data
 * @param $title
 */
function InterfaceLog($data, $title, $type=1){
    \DB::table('interface_log')->insert([
        'text'  => json_encode($data),
        'title'  => $title,
        'type'  => $type,
        'created_at'    => getDt()
    ]);
}

/**
 * 订单初审识别日志
 * @param $data
 * @param $title
 */
function DistLog($data, $orderId){
    \DB::table('users_order_dist')->insert([
        'text'  => json_encode($data),
        'oid'  => $orderId,
        'created_at'    => getDt()
    ]);
}

function getDt(){
    return date('Y-m-d H:i:s');
}

function request_post($url = '', $param = '') {
    if (empty($url) || empty($param)) {
        return false;
    }

    $postUrl = $url;
    $curlPost = $param;
    $curl = curl_init();//初始化curl
    curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($curl);//运行curl
    curl_close($curl);

    return $data;
}

function getAccessToken(){
    $url = 'https://aip.baidubce.com/oauth/2.0/token';
    $post_data['grant_type']       = 'client_credentials';
    $post_data['client_id']      = 'LuYy46MUOLv60p2prdIBdXcb';
    $post_data['client_secret'] = 'EhG1189bYLOWgYl78QohHatcVv5sT0yO';
    $o = "";
    foreach ( $post_data as $k => $v )
    {
        $o.= "$k=" . urlencode( $v ). "&" ;
    }
    $post_data = substr($o,0,-1);

    $res = request_post($url, $post_data);
    if( $res ){
        $data = json_decode($res, true);
        if( isset($data['access_token']) ){
            return $data['access_token'];
        }
    }
    return false;
}

/**
 * 图像识别高精度版
 */
function imgRecognition($imgPath){
    $token = getAccessToken();
    if( !$token ){
        return false;
    }
    $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=' . $token;
    // $img = file_get_contents($imgPath);
    // $img = base64_encode($img);
    $bodys = array(
        'url' => config('app.url').$imgPath,
    );
    $res = request_post($url, $bodys);
    if( $res ){
        $data = json_decode($res, true);
        if( isset($data['words_result']) ){
            return $data['words_result'];
        }
    }
    return false;
}

/**
 * 图像识别高精度版
 */
function imgRecognition2($img){
    $token = getAccessToken();
    if( !$token ){
        return false;
    }
    $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=' . $token;
    $bodys = array(
        'image' => $img,
    );
    $res = request_post($url, $bodys);
    if( $res ){
        $data = json_decode($res, true);
        if( isset($data['words_result']) ){
            return $data['words_result'];
        }
    }
    return false;
}

/**
 * 图像识别标准版
 */
function imgRecognition1($imgPath){
    $token = getAccessToken();
    if( !$token ){
        return false;
    }
    $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=' . $token;
    // $img = file_get_contents($imgPath);
    // $img = base64_encode($img);
    $bodys = array(
        'url' => config('app.url').$imgPath,
    );
    $res = request_post($url, $bodys);
    if( $res ){
        $data = json_decode($res, true);
        if( isset($data['words_result']) ){
            return $data['words_result'];
        }
    }
    return false;
}

function filterSpecialChar($str){
    $str = str_replace('（', '', $str);
    $str = str_replace('(', '', $str);
    $str = str_replace('）', '', $str);
    $str = str_replace(')', '', $str);
    $str = str_replace('·', '', $str);
    $str = str_replace('◆', '', $str);
    $str = str_replace('★', '', $str);
    $str = str_replace('●', '', $str);
    return $str;
}

/**
 * 识别
 * @param $arr
 * @param $orderNo
 * @param $title
 * @param $amount
 * @param $date
 * @return bool
 */
function autoAudit($arr, $orderNo, $title, $amount, $date, &$msg): bool
{
    $amount = (string)$amount;
    $amount = trim(trim(trim($amount, '00'), '0'), '.');

    $title = filterSpecialChar($title);
    $title = mb_substr($title, 0, 15);
    $noStatus = false;
    $titleStatus = false;
    $amountStatus = false;
    $dateStatus = false;
    foreach ($arr as $item) {
        if( $noStatus==false && strpos($item['words'], $orderNo) !== false ){
            $noStatus = true;
        }
        if( $titleStatus==false && strpos(filterSpecialChar($item['words']), $title) !== false ){
            $titleStatus = true;
        }
        if( $amountStatus==false && strpos($item['words'], $amount) !== false ){
            $amountStatus = true;
        }
        if( $dateStatus==false && strpos($item['words'], $date) !== false || strpos($item['words'], date("Y-m-d", strtotime($date)-3600)) !== false || strpos($item['words'], date("Y-m-d", strtotime($date)+3600*25)) !== false ){
            $dateStatus = true;
        }
        if( $noStatus && $titleStatus && $amountStatus && $dateStatus ){
            return true;
        }
    }
    if( !$titleStatus ){
        $msg = "下单店铺有误";
        return false;
    }
    if( !$noStatus ){
        $msg = "订单号有误";
        return false;
    }
    if( !$amountStatus ){
        $msg = "实付金额有误";
        return false;
    }
    if( !$dateStatus ){
        $msg = "下单时间有误";
        return false;
    }
    return false;
}

function completeImg($img): string
{
    return env('domain').$img;
}

function getRestTime($date){
    $hour = intval((strtotime($date) - time()) / 3600);
    $mini = intval(((strtotime($date) - time()) % 3600) / 60);
    return ($hour < 10 ? '0'.$hour:$hour)."小时".($mini < 10 ? '0'.$mini:$mini)."分";
}

